﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class P2Controller : BaseController {

	public GameObject rootPanel;
	//信息板块
	public GameObject scorePanel;
	//图集
	public UIAtlas altas;
	//选牌面板
	public UIPanel pickPanel;
	//牌型面板
	public UIPanel recommendPanel;
	//每局结果面板
	public UIPanel totalPanel;
	//重新开始面板
	public UIPanel restartPanel;
	//特殊牌型面板
	public UIPanel teshuPanel;
	//操作面板
	public UIPanel controllerPanel;
	//消息面板
	public UIPanel messagePanel;
	public List<UISprite> messageBoxs = new List<UISprite>();
	public List<UISprite> playRecords = new List<UISprite>();
	public AudioSource audioSource;
	public AudioSource textMessageSource;
	public AudioSource compareAudioSource;

	//解散面板
	public UIPanel dissolutionPanel;

	//用户信息
	public List<GameObject> players = new List<GameObject>();
	public List<UISprite> pokerSprite = new List<UISprite> ();
	public List<UIPanel> resultPanel = new List<UIPanel>();

	private string _cur = "";

	void Start(){

		//初始化积分面板
		ScoreCompent.ScortInit(scorePanel);
		MessageCompent.MessageInit (messagePanel,messageBoxs,playRecords,audioSource,textMessageSource);
		DissolutionCompent.DissolutionInit (rootPanel, dissolutionPanel);
		ControllerCompent.ControllerInit (controllerPanel);	

		//初始化音效
		if (PlayerPrefs.GetInt (Main.MUSIC) == 0) {
			AudioManager.Instance.Pause ();
		} else {
			AudioManager.Instance.Play ();
		}

		//获取房间配置信息
		API.GetRoomSetting ();

		//在接收者中注册事件及其回调方法
		NotificationCenter.Get().AddEventListener(API.ROOM_ACTION, HandlerRoomFrame);
		NotificationCenter.Get().AddEventListener(API.USER_ACTION, HandlerRoomExit);
		NotificationCenter.Get().AddEventListener(API.ERROR_ACTION, HandlerError);
		NotificationCenter.Get().AddEventListener(API.TEXT_MESSAGE, HandlerTextMessage);
		NotificationCenter.Get().AddEventListener(API.ROOM_SETTING, HandlerSetting);
		NotificationCenter.Get().AddEventListener(API.DISSOLUTION_ROOM_START, HandlerDissolutionRoom);
		NotificationCenter.Get().AddEventListener(API.DISSOLUTION_FAIL, HandlerDissolutionFail);
		NotificationCenter.Get().AddEventListener(API.VOICE_MESSAGE, HandlerVoiceMessage);
		NotificationCenter.Get().AddEventListener(API.RECHARGE_SUCCESS, HandlerRechagerSuccess);
		NotificationCenter.Get().AddEventListener(API.CHECK_SPECIAL, HandlerTeshu);
		NotificationCenter.Get().AddEventListener(API.STASTICS_ROOM, HandlerStastistics);


		LicensingCompent.InitGamingPanel (altas,recommendPanel,pickPanel);
		ResultCompent.InitRestartPanel (totalPanel,restartPanel,altas,compareAudioSource);

		HandlerRoomFrame (null);
//		API.ChangeCard();
	}

	void Update(){
		base.Update ();
		LicensingCompent.Update ();
		MessageCompent.Update ();
	}

	void OnDestroy(){
		Debug.Log ("移除监听");
		NotificationCenter.Get ().RemoveEventListener (API.ROOM_ACTION,HandlerRoomFrame);
		NotificationCenter.Get ().RemoveEventListener (API.USER_ACTION,HandlerRoomFrame);
		NotificationCenter.Get ().RemoveEventListener (API.USER_ACTION,HandlerRoomExit);
		NotificationCenter.Get ().RemoveEventListener (API.ERROR_ACTION,HandlerError);
		NotificationCenter.Get ().RemoveEventListener (API.TEXT_MESSAGE,HandlerTextMessage);
		NotificationCenter.Get ().RemoveEventListener (API.ROOM_SETTING,HandlerSetting);
		NotificationCenter.Get ().RemoveEventListener (API.DISSOLUTION_ROOM_START,HandlerDissolutionRoom);
		NotificationCenter.Get ().RemoveEventListener (API.DISSOLUTION_FAIL,HandlerDissolutionFail);
		NotificationCenter.Get ().RemoveEventListener (API.VOICE_MESSAGE,HandlerVoiceMessage);
		NotificationCenter.Get ().RemoveEventListener(API.RECHARGE_SUCCESS, HandlerRechagerSuccess);
		NotificationCenter.Get ().RemoveEventListener(API.CHECK_SPECIAL, HandlerTeshu);
		NotificationCenter.Get ().RemoveEventListener(API.CHECK_SPECIAL, HandlerStastistics);
	}


	
	void HandlerRoomFrame(object obj){

		//刷新信息板
		ScoreCompent.Refresh();
		//更新控制器信息
		ControllerCompent.HandlerStatus();

//		initPanel ();
		lock(Main.room.players){
			for (int i=0;i< Main.room.players.Count;i++) {
				Main.room.players [i].pokerContainer = pokerSprite [i];
				Main.room.players [i].resultContainer = resultPanel [i];
			}
			for (int i = 0; i < Main.room.playerNum; i++) {
				if (i+1 > Main.room.players.Count) {
					PlayerCompent.Reset (players [i]);
				} else {
					PlayerCompent.PlayerInfo (players [i],Main.room.players[i]);
				}

			}
		}

		if ((Main.user.status == USER_STATUS.UN_READY.GetHashCode() || Main.user.status == USER_STATUS.READY.GetHashCode())
			&& _cur == "show scores") {
			ResultCompent.DestroyPanel ();
		}

		// zhunbei
		if (Main.user.status == USER_STATUS.READY.GetHashCode () || Main.user.status == USER_STATUS.UN_READY.GetHashCode ()) {
			_cur = "ready";
		}



		//gaming
		if (Main.room.status == ROOM_STATUS.GAMEING.GetHashCode () && Main.user.status == USER_STATUS.BEFORE_SUBMIT.GetHashCode ()) {
			
			if (_cur != "gaming") {
				_cur = "gaming";

				// if no self
				for (int i = 1; i < Main.room.players.Count; i++) {
					LicensingCompent.InitHiddenPokers (Main.room.players [i]);	
				}
				// if myself
				LicensingCompent.InitMyPokers ();
				LicensingCompent.AnimationMyPokers ();

				//初始化
				TeShuCompent.TeShuCompentInit (teshuPanel);
				API.CheckSpecial ();
			}

			for (int i = 1; i < Main.room.players.Count; i++) {
				LicensingCompent.ShowHiddenPokers (Main.room.players [i]);
			}
				
			//显示自己的发牌信息
			LicensingCompent.ShowMyPokers();

			//判断其他玩家比分前摆牌状态
			for (int i = 1; i < Main.room.playerNum; i++) {
				LicensingCompent.SwitchHiddenPokers (Main.room.players [i]);	
			}

		} else if (_cur == "gaming") {
			for (int i = 1; i < Main.room.players.Count; i++) {
				LicensingCompent.DestroyHiddenPokers (Main.room.players [i]);
			}
			LicensingCompent.DestroyMyPokers ();
			TeShuCompent.Reset ();
		}

		// after submit
		if (Main.user.status == USER_STATUS.AFTER_SUBMIT.GetHashCode() && Main.room.status == ROOM_STATUS.GAMEING.GetHashCode()) {
			if (_cur != "after submit") {
				_cur = "after submit";

				// if no self
				for (int i = 1; i < Main.room.players.Count; i++) {
					LicensingCompent.InitHiddenPokers (Main.room.players [i],false);	
				}
				// if myself
				LicensingCompent.InitMyPokers (false);
			}

			for (int i = 1; i < Main.room.players.Count; i++) {
				LicensingCompent.ShowHiddenPokers (Main.room.players [i]);
			}

			//显示自己的发牌信息
			LicensingCompent.ShowMyPokers();
			LicensingCompent.SwitchMyPokers ();


			//判断其他玩家比分前摆牌状态
			for (int i = 1; i < Main.room.playerNum; i++) {
				LicensingCompent.SwitchHiddenPokers (Main.room.players [i]);	
			}

		} else if (_cur == "after submit") {
			for (int i = 1; i < Main.room.players.Count; i++) {
				LicensingCompent.DestroyHiddenPokers (Main.room.players [i]);
			}
			LicensingCompent.DestroyMyPokers ();
		}


		if (Main.room.status == ROOM_STATUS.SHOW_SCORES.GetHashCode() && Main.user.status == USER_STATUS.AFTER_SUBMIT.GetHashCode()) {
			if (_cur != "show scores") {
				_cur = "show scores";

				for(int i=1;i<Main.room.players.Count;i++){
					ResultCompent.ResetResultPokers (Main.room.players[i]);
				}
				ResultCompent.ResetMyResultPokers ();
				//动画控制器
				StartCoroutine(ResultCompent.StartAnimation());
			}

			ResultCompent.RestartContinueHandler ();

			// dajia dou gaipai, teshupai yitiao xianshi ,yeshi gipai
			// donghua, 355 fanguolai , yitiao banyuan zhanshi 
			// daqiang /quanleida donghua
			// xianshi jieguomianban
			// dianji likai fangjian
		}else if (_cur == "show scores") {
			ResultCompent.DestroyPanel ();
		}

	}

	void HandlerStastistics(object obj){
		ResultCompent.HandlerStastistics (obj.ToString ());
	}

	void HandlerTeshu(object obj){
		TeShuCompent.ShowMyTeShu (obj.ToString ());
		LicensingCompent.HandlerTeshu (obj.ToString ());
	}

	void HandlerRechagerSuccess(object obj){
		API.RestartGame ();
	}

	void HandlerTextMessage(object obj){
		MessageCompent.HandTextMessage (obj.ToString ());
	}

	void HandlerRoomExit(object obj){
		if (Main.user.status == USER_STATUS.FREE.GetHashCode ()) {
			SceneManager.LoadScene ("Home");
		}
	}

	void HandlerError(object obj){
		ErrorManager.Show(rootPanel,obj.ToString());
	}

	void HandlerSetting(object obj){
		DissolutionCompent.Setting (obj.ToString ());
	}

	//监听解散房间
	void HandlerDissolutionRoom(object obj){
		DissolutionCompent.StartDisSolution (obj.ToString ());
	}

	//解散失败
	void HandlerDissolutionFail(object obj){
		JSONObject json = new JSONObject (obj.ToString ());
		ErrorManager.ShowString(rootPanel,json["reason"].str);
		DissolutionCompent.DissolutionFail ();
	}

	//接收语音消息
	void HandlerVoiceMessage(object obj){
		MessageCompent.handVoiceMessage (obj.ToString ());
	}
}
